<template>
  <div class="pages_content table">
    <el-container>
      <el-header>
        <breaDcrumb />
      </el-header>
      <el-main style="display:flex">
        <div>
          <div class="header_right" @click="showCardNav = !showCardNav">
            <div class="title">搜索</div>
            <div>
              <transition name="from"></transition>
              <span v-show="!showCardNav">
                <i style="margin-right: 5px;" class="el-icon-arrow-down"></i>
              </span>
              <transition name="to"></transition>
              <span v-show="showCardNav">
                <i style="margin-right: 5px;" class="el-icon-arrow-up"></i>
              </span>
            </div>
          </div>
          <div v-show="showCardNav" class="hr"></div>
          <el-collapse-transition>
            <div v-show="showCardNav">
              <div class="search">
                <span style="display: inline-block;margin-bottom: 10px;">
                  <span style="margin-right: 12px;">站点名称</span>
                  <el-input v-model="tableParam.station" style="width: 240px;" clearable placeholder="请输入" @keyup.enter.native="gettableData()" />
                </span>
                <span style="margin-left: 24px;">
                  <span style="margin-right: 12px;">原物料名称</span>
                  <el-input v-model="tableParam.materials" style="width: 240px;" clearable placeholder="请输入" @keyup.enter.native="gettableData()" />
                </span>
                <el-button icon="el-icon-search" size="medium" class="bottom_all but1" @click="(tableParam.page = 1), gettableData()">查 询</el-button>
                <el-button size="medium" class="bottom_all_two" style="margin-left:12px;" @click="init()">重 置</el-button>
              </div>
            </div>
          </el-collapse-transition>
          <div class="hr"></div>
          <div class="card">
            <div class="card_nav">
              <div>
                <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='TIANJIA'))!==-1" size="small" class="bottom_all" style="margin-left: 0;" @click="addFromDate('添加'),list=[]">
                  <i class="icon iconfont iconicon_button_add" style="font-size: 12px;"></i>
                  添加
                </el-button>
              </div>
            </div>
            <div v-loading="tableLoading" class="card_info" :style="style">
              <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width:100%" :data="tableData" tooltip-effect="dark">
                <template v-for="(item, index2) in table">
                  <el-table-column v-if="item.status" :key="index2" :label="item.label" align="center" :width="item.width">
                    <template slot-scope="scope">
                      <el-button v-if="item.label == '供应详情'&&ButtonList.findIndex(res=>(res.buttonValue=='GONGYINGXQ'))!==-1" size="mini" class="bottom_one" @click="showdetails(scope.row)">供应详情</el-button>
                      <span v-else>{{ scope.row[item.prop] }}</span>
                    </template>
                  </el-table-column>
                </template>
              </el-table>
            </div>
            <div class="card_bottom">
              <div class="card_bottom_left">
                <div class="top_page_totle">总共{{ total }}条</div>
                <el-pagination :current-page.sync="tableParam.page" :page-size="tableParam.pageSize" layout="prev, pager, next, jumper" :total="total" @current-change="gettableData()"></el-pagination>
              </div>
              <div>
                <el-button size="mini" icon="el-icon-refresh-right" class="bottom_all_two" @click="gettableData">刷新</el-button>
              </div>
            </div>
          </div>
        </div>
      </el-main>
    </el-container>
    <!-- 添加 -->
    <el-dialog v-dialogDrag :visible.sync="addDialog" width="1200px" :close-on-click-modal="false" :before-close="resetFromDate">
      <span slot="title" class="dialog-title">{{ addDialogTitle }}</span>
      <div>
        <el-form ref="reffromDate" :rules="rules" :inline="true" :model="fromDate" label-width="100px">
          <el-form-item v-if="UserInfo.adminStatus == 1" prop="companyId">
            <span slot="label" style="color:#FF0000;">公司</span>
            <el-select ref="selection1" v-model="fromDate.companyId" placeholder="请选择" @change="setstationIdlist(),$nextTick(()=>{fromDate.companyName = $refs.selection1.selectedLabel})">
              <el-option v-for="(item, index) in companyIdlist" :key="index" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="stationId">
            <span slot="label" style="color:#FF0000;">站点</span>
            <el-select ref="selection2" v-model="fromDate.stationId" placeholder="请选择" :disabled="stationIdlist.length==0" @change="setlist(),get_simple_organizationFun(fromDate.stationId),$nextTick(()=>{fromDate.station = $refs.selection2.selectedLabel})">
              <el-option v-for="(item, index) in stationIdlist" :key="index" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="materialsId">
            <span slot="label" style="color:#FF0000;">原物料名称</span>
            <el-select v-model="fromDate.materialsId" placeholder="请选择" @change="setlist()">
              <el-option v-for="(item, index) in materialsIdlist" :key="index" :label="item.itemName" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="practiceNumer">
            <span slot="label" style="color:#FF0000;">需求总量(吨)</span>
            <el-input-number v-model="fromDate.practiceNumer" style="width:100px" :controls="false" :precision="0"></el-input-number>
          </el-form-item>
          <el-form-item prop="needDate">
            <span slot="label" style="color:#FF0000;">需求日期：</span>
            <el-date-picker v-model="fromDate.needDate" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间"></el-date-picker>
          </el-form-item>
        </el-form>
        <div>
          <span class="dialog-title">原物料供应详情</span>
          <el-button size="mini" class="bottom_three" style="margin-left:40px;" @click="getplanlist()">获取计划</el-button>
          <el-button size="mini" class="bottom_all" style="margin-left: 12px;" @click="addItem()">
            <i class="icon iconfont iconicon_button_add" style="font-size: 12px;"></i>
            添加
          </el-button>
        </div>
        <div style="padding-top:10px">
          <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width:100%" :data="fromDate.list" tooltip-effect="dark">
            <el-table-column label="合同编号" align="center">
              <template slot-scope="scope">
                <el-select v-if='!scope.row.isReadOnly' v-model="scope.row.contractId" :disabled='scope.row.isReadOnly' placeholder="请选择" style="width:100%" @change="changeitem(scope.row)">
                  <el-option v-for="(item, index) in list" :key="index" :label="item.contractNo+'：'+item.supplier" :value="item.contractId"></el-option>
                </el-select>
                <span v-else>{{scope.row.contractNo}}：{{scope.row.supplier}}</span>
              </template>
            </el-table-column>
            <el-table-column label="原物料供应商" align="center" prop="supplierName"></el-table-column>
            <el-table-column label="原物料" align="center">
              <template slot-scope="scope">
                <el-select v-if='!scope.row.isReadOnly' v-model="scope.row.rawMaterialsId" placeholder="请选择" style="width:100%" @change="change1(scope.row)">
                  <el-option v-for="(item, index) in scope.row.list" :key="index" :label="item.productName+'_'+item.specification+'_'+item.brand" :value="item.productId"></el-option>
                </el-select>
                <span v-else>{{scope.row.rawMaterialsName}}</span>
              </template>
            </el-table-column>
            <el-table-column label="规格" align="center" prop="specification"></el-table-column>
            <el-table-column label="品牌" align="center" prop="brand"></el-table-column>
            <el-table-column label="份额" align="center" prop="supplierPercent">
              <template slot-scope="scope">
                <span v-if='!scope.row.isReadOnly'>/</span>
                <span v-else>{{scope.row.supplierPercent+'%'}}</span>
              </template>
            </el-table-column>
            <el-table-column label="是否含运输" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.transportStatus==1" style="color:#00A754;">是</span>
                <span v-else style="color:#969799;">否</span>
              </template>
            </el-table-column>
            <el-table-column label="供应量" align="center">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.supplierNumber" style="width:100%" :controls="false" :precision="2"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="车辆外包合同" align="center" prop="carContractNo">
              <template slot-scope="scope">
                <span v-if="scope.row.transportStatus==1">{{scope.row.carContractNo}}</span>
                <span v-else>
                  <el-select v-model="scope.row.carContractId" placeholder="请选择" style="width:100%" :disabled="scope.row.contractId && scope.row.rawMaterialsId?false:true" @change="change2(scope.row)" @visible-change="getplanData1(scope.row)">
                    <el-option v-for="(item, index) in scope.row.planData1" :key="index" :label="item.contractNumber+'：'+item.cargo" :value="item.contractId"></el-option>
                  </el-select>
                </span>
              </template>
            </el-table-column>
            <el-table-column label="车辆供应商" align="center" prop="carCompanyName"></el-table-column>
            <el-table-column label="操作" align="left" width="120">
              <template slot-scope="scope">
                <el-button size="mini" class="bottom_two" @click="deleteItem(scope.$index)">
                  <i class="icon iconfont iconicon_button_delete" style="font-size: 12px;"></i>
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="resetFromDate">取 消</el-button>
        <el-button class="bottom_all" style="margin-left: 24px;" @click="pagessubmitFromDate()">提交申请</el-button>
      </span>
    </el-dialog>
    <!-- 查看详情 -->
    <el-dialog v-dialogDrag :visible.sync="detailsDialog" width="1015px" :close-on-click-modal="false">
      <span slot="title" class="dialog-title">查看详情</span>
      <div class="dialoginfo">
        <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width:100%" :data="infolist" tooltip-effect="dark">
          <el-table-column label="原物料合同编号" align="center" prop="contractNo"></el-table-column>
          <el-table-column label="原物料供应商" align="center" prop="supplierName"></el-table-column>
          <el-table-column label="原物料" align="center" prop="rawName"></el-table-column>
          <el-table-column label="规格" align="center" prop="specification"></el-table-column>
          <el-table-column label="品牌" align="center" prop="brand"></el-table-column>
          <el-table-column label="供应量" align="center" prop="supplierNumber"></el-table-column>
          <el-table-column label="是否含运输" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.transportStatus==0" style="color:#969799;">否</span>
              <span v-else style="color:#00A754;">是</span>
            </template>
          </el-table-column>
          <el-table-column label="车辆租赁合同编号" align="center" prop="carContractNo"></el-table-column>
          <el-table-column label="车辆租赁供应商" align="center" prop="carCompanyName"></el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="detailsDialog=false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import mixin from "@/mixins/ICPSmixin.js";
import {
  queryPage,
  saveOrUpdate,
  Download,
  getPlanDetailById,
  getLotAllotsByStation,
  getContractCarByCondition,
} from "@/api/GHnumber/DSPplorder.js";
import { getUserInfo } from "@/utils/auth.js";
import { getcompany, getUserAutList, get_simple_organization, getDicType } from "@/api/common.js";
import { get_station_list } from "@/api/smart/stocksake.js";
import { getContracts } from "@/api/GHnumber/share.js";
export default {
  mixins: [mixin],
  data() {
    return {
      UserInfo: '',
      /*表格增删改查及下载接口*/
      queryPage: queryPage,
      saveOrUpdate: saveOrUpdate,
      DownloadURL: Download,
      /*表格数据*/
      table: [
        { label: "站点名称", width: "120", prop: "station", status: true },
        { label: "原物料名称", width: "auto", prop: "materials", status: true },
        {
          label: "需求总量",
          width: "120",
          prop: "practiceNumer",
          status: true,
        },
        { label: "供应详情", width: "auto", prop: "", status: true },
        { label: "生成时间", width: "auto", prop: "createTime", status: true },
        { label: "需求日期", width: "auto", prop: "needDate", status: true },
      ],
      pagesType: 0,
      /*添加表单数据*/
      rules: {
        companyId: [
          { required: true, message: "请选择公司", trigger: "change" },
        ],
        stationId: [
          { required: true, message: "请选择站点", trigger: "change" },
        ],
        practiceNumer: [
          { required: true, message: "请输入需求总量", trigger: "blur" },
        ],
        needDate: [
          { required: true, message: "请选择需求日期", trigger: "change" },
        ],

        materialsId: [
          { required: true, message: "请选择原物料", trigger: "change" },
        ],
      },
      companyIdlist: [],
      stationIdlist: [],
      materialsIdlist: [],
      fromDate: {
        stationId: "",
        companyId: "",
        practiceNumer: "",
        needDate: "",
        materialsId: "",
        dataType: 1,
        list: [],
      },
      list: [],
      infolist: [],
      detailsDialog: false,
      planData1: [],
    };
  },
  async created() {
    this.UserInfo = await getUserInfo();
    if (this.UserInfo.adminStatus == 1) {
      /**通过typeId为公司类型id查询所有公司 */
      getcompany({ typeId: "19da56b9e85648059e3cf1e7da497da4" }).then((res) => {
        this.companyIdlist = res.data;
      });
    } else {
      this.stationIdlist = await getUserAutList(true)
    }
    /*存储拷贝的原初始化fromDate数据*/
    this.tableParam = { ...this.tableParam, station: "", materials: "" };
    this.gettableData();
    getDicType({ code: "MATname" }).then((res) => {
      this.materialsIdlist = res.data.items;
    });
    /**
     * @Description: 获取车辆外包合同
     * @Param: 
     * @Author: wangwangwang
     */
  },
  methods: {
    /**查询当前原物料合同的车辆外包合同 */
    getplanData1(row) {
      getContractCarByCondition({ contractId: row.contractId, rawId: row.rawMaterialsId, stationId: this.fromDate.stationId }).then((res) => {
        if (res.data.length > 0) {
          row.planData1 = res.data
        } else {
          this.$message({
            message: "车辆外包合同空！",
            type: "warning",
          });
          row.planData1 = []
        }
        this.$forceUpdate()
      })
    },
    /**通过站点查询公司 */
    get_simple_organizationFun(id) {
      get_simple_organization({ id: id }).then((res) => {
        this.fromDate.companyId = res.data.id
        this.fromDate.companyName = res.data.name
      });//查询站点所属公司
    },
    /*重置数据*/
    init() {
      this.tableParam.materials = "";
      this.tableParam.station = "";
      this.gettableData();
    },
    /*添加*/
    addItem() {
      let item = {
        contractId: "",
        contractNo: "",
        supplierId: "",
        supplierName: "",
        rawId: "",
        rawName: "",
        supplierPercent: "",
        transportStatus: null,
        supplierNumber: "",
        carContractId: "",
        carContractNo: "",
        carCompanyId: "",
        carCompanyName: "",
        specification: "",
        brand: "",
        list: [],
      };
      this.fromDate.list.push(item);
    },
    deleteItem(index) {
      this.fromDate.list.splice(index, 1);
    },
    /*保存*/
    pagessubmitFromDate() {
      let _this = this;
      _this.fromDate.planStatus = 2;
      _this.$refs.reffromDate.validate((valid) => {
        if (valid) {
          if (_this.fromDate.list.length == 0) {
            _this.$message({
              message: "警告哦，请至少添加一条计划",
              type: "warning",
            });
            return;
          }
          if (!_this.fromDate.list.every((v) => {
            if (v.transportStatus == 1) {
              if (v.contractId != '' && v.rawMaterialsId != '') {
                return true
              } else {
                return false
              }
            } else {
              if (v.contractId != '' && v.rawMaterialsId != '' && v.carContractNo != '') {
                return true
              } else {
                return false
              }
            }
          })) {
            _this.$message({
              message: "其检查表格数据是否填写完整！",
              type: "warning",
            });
            return
          }
          let sum = 0;
          for (var i = 0, len = _this.fromDate.list.length; i < len; i++) {
            sum += _this.fromDate.list[i].supplierNumber
          }
          if (sum > _this.fromDate.practiceNumer) {
            _this.$message({
              message: "供应量不能大于需求总量",
              type: "warning",
            });
            return;
          }
          _this.fromDate.materials = _this.$fromatTable(
            _this.materialsIdlist,
            _this.fromDate.materialsId,
            "id",
            "itemName"
          );
          const copyData = JSON.parse((JSON.stringify(_this.fromDate)));
          copyData.list = JSON.stringify(copyData.list);
          this.addDialog = false
          _this.$router.push({ name: 'PurchaseOrder', query: { ...copyData, type: 1 } })
        }
      });
    },
    /*供应详情*/
    showdetails(low) {
      getPlanDetailById({ id: low.id }).then((res) => {
        this.infolist = res.data;
      });
      this.detailsDialog = true;
    },
    /*根据公司获取站点，站点原物料变化时置空*/
    setstationIdlist() {
      get_station_list({ parentId: this.fromDate.companyId }).then((res) => {
        this.stationIdlist = res.data;
      });
      this.fromDate.stationId = "";
      this.fromDate.list = [];
      this.list = [];
    },
    setlist() {
      /**
      * @Description: 设置默认值
      * @Param: 
      * @Author: wangwangwang
      */
      if (!this.fromDate.stationId) return
      if (!this.fromDate.materialsId) return
      /**
       * @Description: 通过站点和原物料获取合同号
       * @Param: 
       * @Author: wangwangwang
       */
      const params = {
        id: this.fromDate.materialsId,
        stations: this.fromDate.stationId,
      }
      getContracts(params).then(res => {
        if (res.code === 1001) {
          this.fromDate.list = []
          this.list = res.data;
          if (!res.data.length) {
            this.$message.warning('合同编号为空');
            return;
          }
        }
      })
    },
    /*获取计划*/
    getplanlist() {
      if (!this.fromDate.stationId) {
        this.$refs.reffromDate.validateField("stationId");
        return;
      }
      if (!this.fromDate.materialsId) {
        this.$refs.reffromDate.validateField("materialsId");
        return;
      }
      if (!this.fromDate.practiceNumer) {
        this.$refs.reffromDate.validateField("practiceNumer");
        return;
      }
      getLotAllotsByStation({
        stationId: this.fromDate.stationId,
        rawId: this.fromDate.materialsId,
      }).then((res) => {
        if (res.code === 1001) {
          if (res.data.length == 0) {
            this.$message.warning('计划为空');
          }
          const newData = res.data.map(item => ({ ...item, isReadOnly: true, supplierName: item.supplier, supplierPercent: item.lotNum, transportStatus: item.isCarriage, supplierNumber: this.fromDate.practiceNumer * item.lotNum * 0.01, rawName: item.rawMaterialsName, id: '' }));
          this.fromDate.list = newData;
        }
      });
    },
    /*拉取数据*/
    changeitem(item) {
      let data = this.list.find((res) => res.contractId == item.contractId);
      console.log(JSON.parse(JSON.stringify(data)))
      item.contractNo = data.contractNo;
      item.list = data.list;
      item.companyId = data.companyId;
      item.company = data.company;
      item.supplierId = data.supplierId;
      item.supplierName = data.supplier;
      item.transportStatus = data.isCarriage;
      item.rawMaterialsId = '';
      item.specification = '';
      item.brand = '';
      item.carContractNo = '';
      item.carCompanyId = '';
      item.carCompanyName = '';
      item.supplierNumber = '';
      item.planData2 = []
      item.carContractId = '';
    },
    change1(item) {
      let data = item.list.find(
        (res) => res.productId == item.rawMaterialsId
      );
      item.rawId = data.productId;
      item.rawName = data.productName;
      item.brand = data.brand;
      item.specification = data.specification;
      item.carContractId = '';
      item.carContractNo = '';
      item.carCompanyId = '';
      item.carCompanyName = '';
    },
    change2(item) {
      let data = item.planData1.find((res) => res.contractId == item.carContractId);
      item.carContractNo = data.contractNumber;
      item.carCompanyId = data.supplierId;
      item.carCompanyName = data.supplierName;
    },
  },
};
</script>

<style lang="scss" scoped>
.dialog-title {
  font-size: 16px;
  font-weight: bold;
  padding-right: 40px;
}
.el-input,
.el-select {
  width: 240px;
}
.table_link {
  margin: 0 10px;
  color: $bg_color;
}

.table_link:hover {
  opacity: 0.8;
}
</style>
